package pub.guoxin.oops.common.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import pub.guoxin.oops.common.auth.JwtUserVo;
import pub.guoxin.oops.constants.OopsJwtConstants;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import static pub.guoxin.oops.common.auth.utils.DeviceAudienceEnum.AUDIENCE_MOBILE;
import static pub.guoxin.oops.common.auth.utils.DeviceAudienceEnum.AUDIENCE_TABLET;

@Slf4j
@Component
public class JwtTokenUtil implements Serializable {

//    static final String CLAIM_KEY_USERNAME = "sub";
//    static final String CLAIM_KEY_AUDIENCE = "aud";
//    static final String CLAIM_KEY_CREATED = "iat";

    private static final long serialVersionUID = -3301605591108950415L;

    public static void main(String[] args) {
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Map<String, Object> claims = new HashMap<>();
        String s = jwtTokenUtil.doGenerateToken(claims, "123456");
        System.out.println(s);

        String usernameFromToken = jwtTokenUtil.getUsernameFromToken("eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNzcxODQ4NTM1NCIsImV4cCI6MTUxNDAyMjE4MSwiaWF0IjoxNTEzNDE3MzgxfQ.FM_k70ipLuTHwJnVLqPwHfUSF7mwbFlxHZ98qW4IBctzkaQfchEJeGmocnruyerfZY8g6NLr7KeaOQT4J243rg");
        System.out.println(usernameFromToken);

    }

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public String getAudienceFromToken(String token) {
        return getClaimFromToken(token, Claims::getAudience);
    }

    private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(OopsJwtConstants.SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, username);
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = TimeProvider.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        log.info("Generate Token " + createdDate);

        return Jwts.builder().setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, OopsJwtConstants.SECRET)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
        final Date created = getIssuedAtDateFromToken(token);
        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
                && (!isTokenExpired(token) || ignoreTokenExpiration(token));
    }

    public String refreshToken(String token) {
        final Date createdDate = TimeProvider.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        final Claims claims = getAllClaimsFromToken(token);
        claims.setIssuedAt(createdDate);
        claims.setExpiration(expirationDate);

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, OopsJwtConstants.SECRET)
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        JwtUserVo user = (JwtUserVo) userDetails;
        final String username = getUsernameFromToken(token);
        final Date created = getIssuedAtDateFromToken(token);
        //final Date expiration = getExpirationDateFromToken(token);
        return (
                username.equals(user.getMobile())
                        && !isTokenExpired(token)
                        && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())
        );
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(TimeProvider.now());
    }

    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    private Boolean ignoreTokenExpiration(String token) {
        String audience = getAudienceFromToken(token);
        return (AUDIENCE_TABLET.getValue().equals(audience) || AUDIENCE_MOBILE.getValue().equals(audience));
    }

    /**
     * 计算到期日期
     *
     * @param createdDate
     * @return
     */
    private Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + OopsJwtConstants.EXPIRATION * 1000);
    }
}
